package Http

import (
	"Volta/Config"
	"Volta/Core/Container"
	"Volta/App/Http/Route"
	"github.com/gin-gonic/gin"
	"reflect"
	"strconv"
)
type HttpEngine struct{}
/**
 * 启动gin引擎
 * @wiki https://github.com/fvbock/endless#signals
 */
//func runEngine(engine *gin.Engine, addr string, pidPath string) error {
	//设置gin调试模式
	//if !GetDebug() {
	//	gin.SetMode(gin.ReleaseMode)
	//}
	//
	//server := endless.NewServer(addr, engine)
	//server.BeforeBegin = func(add string) {
	//	pid := syscall.Getpid()
	//	if gin.Mode() != gin.ReleaseMode {
	//		fmt.Printf("Actual pid is %d \n\r", pid)
	//	}
	//	WritePidFile(pidPath, pid)
	//}
	//err := server.ListenAndServe()
	//return err
//}

// Start proxy with config file
//@reviser sam@2020-04-06 10:10:09
func (s *HttpEngine) RunEngine(registerRoute func(*gin.Engine)) {
	//设置gin调试模式
	if !GetDebug() {
		gin.SetMode(gin.ReleaseMode)
	}
	//配置路由引擎
	engine := gin.New()
	registerRoute(engine)
	addr := Config.Server.HttpAddr + ":" + strconv.Itoa(Config.Server.HttpPort)
	engine.Run(addr)
	return
}

//给外部获取启动服务的debug模式
//@author  sam@2020-04-13 17:38:26
func GetDebug() bool {
	return Config.Server.HttpDebug
}

func Execute() func(appNm string){
	return func(appNm string){
		instance, err := Container.App.Make(appNm)
		if err != nil {
			return
		}
		method := instance.ConValue.MethodByName(instance.Method)
		if !method.IsValid() {
			return
		}
		go begin(func() {
			fun := make([]reflect.Value,1)
			fun[0] = reflect.ValueOf(Route.RegisterRoute)
			method.Call(fun)
		})
	}
}
func begin(work func())  {
	work()
}
